<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="90%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      @submit.prevent
    >
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入模板名称" />
      </el-form-item>
<!--      <el-form-item label="模板存储路径" prop="path">-->
<!--        <el-input v-model="formData.path" placeholder="请输入模板存储路径" />-->
<!--      </el-form-item>-->
      <div>
        <div id="gjs"></div>
      </div>

    </el-form>
    <template #footer>
      <el-button id="export-btn"  @click="explortHtml">导出网页</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TemplatesApi, TemplatesVO } from '@/api/cms/templates'
import {getAccessToken} from "@/utils/auth";
import 'grapesjs/dist/css/grapes.min.css';
import grapesjs from 'grapesjs';
import zh from 'grapesjs/locale/zh';

/** 模板 表单 */
defineOptions({ name: 'TemplatesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  path: undefined,
  content: undefined,
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const token = getAccessToken()

let editor = null

const initGrapesJS = () => {
   editor = grapesjs.init({
    container: '#gjs', // 指定一个容器 ID
    fromElement: true,
     i18n: {
       // locale: 'en', // default locale
       // detectLocale: true, // by default, the editor will detect the language
       // localeFallback: 'en', // default fallback
       messages: { zh },
     },
    height: '50vh',
    width: '100%',
    noticeOnUnload: false,
    storageManager: false,
    plugins: ['gjs-preset-webpage'],
    pluginsOpts: {
      'gjs-preset-webpage': {}
    },
    // assetManager: {
    //     // Upload endpoint, set `false` to disable upload, default `false`
    //     upload: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL +'/infra/file/grapesjs/upload',
    //
    //     // The name used in POST to pass uploaded files, default: `'files'`
    //     uploadName: 'file',
    //     headers: {
    //       Authorization: `Bearer ${token}`,
    //    },
    // },
    blockManager: {
      categories: [
        { id: '基础元素', label: '基础元素' },
        { id: 'media', label: '媒体元素' },
        { id: 'forms', label: '表单元素' }
      ],
      blocks: [
        {
          id: 'section',
          category: '基础元素',
          label: '区域',
          attributes: { class: 'gjs-block-section' },
          content: `<section style="padding: 20px; border: 1px solid #ccc;">
                                <h1>区域标题</h1>
                                <p>区域内容</p>
                            </section>`
        },
        {
          id: 'text',
          category: '基础元素',
          label: '文本',
          content: '<div class="gjs-text" style="padding: 10px;">在此插入文字</div>'
        },
        {
          id: 'image',
          category: 'media',
          label: '图片',
          content: {
            type: 'image',
            style: { 'max-width': '100%' },
            attributes: { alt: '示例图像' }
          }
        },
        {
          id: 'button',
          category: 'forms',
          label: '按钮',
          content: '<button class="gjs-btn">点击我</button>'
        },
        {
          id: 'link',
          category: '基础元素',
          label: '链接',
          content: '<a href="#" class="gjs-link">链接</a>'
        }
      ]
    }
  })



  editor.I18n.addMessages({
    zh: {
      // indicate the locale to update
      deviceManager: {
        device: '设备',
        devices: {
          desktop: '桌面',
          tablet: '平板',
          mobileLandscape: '手机横屏',
          mobilePortrait: '手机竖屏'
        }
      },
    },
  });

  if(formData.value.content){
    editor.loadProjectData(JSON.parse(formData.value.content))
  }else{
    editor.addComponents(`<div style="width: 100%; text-align: center; padding: 20px;">
    请添加网页内容
  </div>`);
  }

  editor.Components.addType('cmp-Y', {
    // Detect '.el-Y' elements
    isComponent: (el) => el.classList?.contains('el-Y'),
    model: {
      defaults: {
        name: 'Component Y', // Simple custom name
        draggable: '.el-X', // Add `draggable` logic
      },
    },
  });

  // 自定义组件类型
  editor.Components.addType('my-carousel', {
    model: {
      defaults: {
        tagName: 'div',
        draggable: true,
        droppable: true,
        attributes: { class: 'my-carousel' },
        components: [
          { type: 'image', src: 'image1.jpg' },
          { type: 'image', src: 'image2.jpg' },
        ],
      },
    },
    view: {
      // 自定义视图逻辑
    },
  });


}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TemplatesApi.getTemplates(id)
    } finally {
      formLoading.value = false
    }
  }


  // 使用 nextTick 确保 DOM 已渲染
  await nextTick()
  initGrapesJS()



}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  formData.value.content=JSON.stringify(editor.getProjectData())
  debugger
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TemplatesVO
    if (formType.value === 'create') {
      await TemplatesApi.createTemplates(data)
      message.success(t('common.createSuccess'))
    } else {
      await TemplatesApi.updateTemplates(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    path: undefined,
  }
  formRef.value?.resetFields()
}

const explortHtml=()=>{
  console.log(editor.getProjectData());
  const html = editor.getHtml();
  const css = editor.getCss();
  const content = `<!DOCTYPE html>
                                <html>
                                <head>
                                <style>${css}</style>
                                </head>
                                <body>${html}</body>
                                </html>`;

  const blob = new Blob([content], { type: 'text/html' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'exported-page.html';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

</script>
<style lang="scss" scoped>
#gjs {
  height: 100vh;
  border: 1px solid #ccc;
}

</style>
